<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="onOkButtonClick"
    :width="taskExecuteInfo.checkrecordid ? '1400px' : '700px'"
    centered
    :footer="null"
  >
    <div style="display: flex; flex-direction: row">
      <a-descriptions
        bordered
        :column="2"
        size="middle"
        style="flex: 1"
        :labelStyle="{ width: '140px' }"
        width="700"
      >
        <a-descriptions-item label="任务项名称" :span="2">{{
          taskExecuteInfo?.item?.itemname
        }}</a-descriptions-item>
        <a-descriptions-item label="单元" :span="2">{{
          taskExecuteInfo?.unitname
        }}</a-descriptions-item>
        <a-descriptions-item label="执行起止时间" :span="1"
          >{{ moment(taskExecuteInfo.begintm).format('YYYY-MM-DD') }}~{{
            moment(taskExecuteInfo.endtm).format('YYYY-MM-DD')
          }}</a-descriptions-item
        >
        <a-descriptions-item label="执行时间" :span="1">{{
          taskExecuteInfo?.executetmstr
        }}</a-descriptions-item>

        <a-descriptions-item label="执行人员" :span="2">{{
          taskExecuteInfo?.executor
        }}</a-descriptions-item>
        <a-descriptions-item label="是否执行完成" :span="1"
          ><a-tag :color="taskExecuteInfo?.hasexec ? 'green' : 'red'">{{
            taskExecuteInfo?.hasexec ? '是' : '否'
          }}</a-tag></a-descriptions-item
        >
        <a-descriptions-item label="是否执行正常" :span="1"
          ><a-tag :color="taskExecuteInfo?.isnormal ? 'green' : 'red'">{{
            taskExecuteInfo?.isnormal ? '是' : '否'
          }}</a-tag></a-descriptions-item
        >
        <a-descriptions-item label="确认时间" :span="1">{{
          taskExecuteInfo?.confirmtm ? moment(taskExecuteInfo.confirmtm).format('YYYY-MM-DD') : '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="确认人" :span="1">{{
          taskExecuteInfo?.confirmusername ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="执行内容描述" :span="2">{{
          taskExecuteInfo?.execdescription ?? '-'
        }}</a-descriptions-item>
        <a-descriptions-item label="执行附件" :span="2">
          <div v-if="taskExecuteInfo?.execattachment?.length > 0" class="flex-row">
            <div v-for="item in taskExecuteInfo?.execattachment" style="margin: 0 2px">
              <a-image
                v-if="item.type === 'jpg' || item.type === 'png' || item.type === 'jpeg'"
                :width="100"
                style="margin: 5px"
                :key="item.id"
                :src="getImageFileUrlPrefix + item.id"
              />
              <div v-else>
                <FilePdfOutlined
                  v-if="item.type === 'pdf'"
                  @click="downloadFile(item)"
                  class="fileIconList"
                />
                <FilePptOutlined
                  v-else-if="item.type === 'ppt'"
                  @click="downloadFile(item)"
                  class="fileIconList"
                />
                <FileWordOutlined
                  v-else-if="item.type === 'doc'"
                  @click="downloadFile(item)"
                  class="fileIconList"
                />
                <FileTextOutlined v-else @click="downloadFile(item)" class="fileIconList" />
              </div>
            </div>
          </div>
          <!-- <a-list
            class="Alist"
            item-layout="horizontal"
            v-if="taskExecuteInfo?.execattachment?.length > 0"
            :data-source="taskExecuteInfo?.execattachment"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a @click="downloadFile(item)">下载</a>
                </template>
                <a-list-item-meta>
                  <template #title>
                    <span>{{ item.title }}</span>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list> -->
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="签名" :span="2">
          <a-image
            :src="getImageFileUrlPrefix + taskExecuteInfo.execsign"
            :width="150"
            v-if="taskExecuteInfo?.execsign"
          />
          <span v-else>-</span>
        </a-descriptions-item>
      </a-descriptions>
      <div v-if="taskExecuteInfo.checkrecordid" style="margin-left: 10px; flex: 1">
        <h2 style="font-weight: 600; font-size: 14px">{{ checkFormData?.content?.title }}</h2>
        <div style="height: 430px">
          <BasicTable
            @register="registerCheckFormTable"
            :can-resize="true"
            :bordered="true"
            :striped="true"
            :data-source="checkFormData?.dataSource"
          >
            <template #description="{ record }">
              <div style="text-align: left">{{ record.description }}</div>
            </template>
            <template #images="{ record }">
              <div
                v-for="(item, index) in record.images"
                :key="item.id"
                style="
                  display: flex;
                  justify-content: space-between;
                  padding: 5px 8px;
                  align-items: center;
                "
              >
                <span style="color: #4fa8ff; font-size: 18px"
                  ><PictureOutlined
                    v-if="
                      item.type == 'png' || item.type == 'jpg' || item.type == 'jpeg'
                    " /><FileTextOutlined v-else /></span
                ><a @click="downloadFile(item)">下载</a>
              </div>
            </template>
            <!-- <template #toolbar>
              <a-button @click="exportInUserToExcel"> 导出Excel </a-button>
            </template> -->
          </BasicTable>
        </div>
      </div>
      <ViewCheckFormInfo @register="registerViewCheckFormModal" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTable, useTable } from '/@/components/Table';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { getOneExecuteRecord } from '/@/api/ehs/taskExecute';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadByUrl } from '/@/utils/file/download';
  import { useGlobSetting } from '/@/hooks/setting';
  import { getImageFileApi, getFileApi } from '/@/api/platform/file';
  import { getCheckRecord } from '/@/api/ehs/checkForm';
  import ViewCheckFormInfo from '/@/views/ehs/checkForm/ViewCheckFormInfo.vue';
  import { checkFormColumns } from './taskBench.data';
  import {
    PictureOutlined,
    FileTextOutlined,
    FilePdfOutlined,
    FilePptOutlined,
    FileWordOutlined,
    FileTextOutlined,
  } from '@ant-design/icons-vue';
  const { createMessage } = useMessage();
  import moment from 'moment';
  export default defineComponent({
    components: {
      BasicModal,
      BasicForm,
      ViewCheckFormInfo,
      BasicTable,
      PictureOutlined,
      FileTextOutlined,
      FilePdfOutlined,
      FilePptOutlined,
      FileWordOutlined,
      FileTextOutlined,
    },
    name: 'ExecuteRecordInfoView',
    emits: ['success'],
    setup() {
      const { uploadUrl } = useGlobSetting();
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getImageFileApi);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const dataId = ref();
      const taskExecuteInfo = ref({});
      const checkFormData = ref({});
      const [registerViewCheckFormModal, { openModal: openViewCheckFormModal }] = useModal();
      /**
       * 检查表table
       */
      const [registerCheckFormTable] = useTable({
        title: checkFormData.value?.content?.title,
        columns: checkFormColumns, //表头数据
        showTableSetting: false, //是否显示表格设置
        bordered: true,
        ellipsis: false,
        striped: false, //斑马纹
        showIndexColumn: false,
        pagination: false,
        size: 'small',
        scroll: { y: 450 },
      });

      const [register, { closeModal }] = useModalInner((data) => {
        checkFormData.value = {};
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          dataId.value = unrefData.dataId;
          getOneExecuteRecord(dataId.value).then((res) => {
            taskExecuteInfo.value = {
              ...res,
              execattachment: res.execattachment ? returnAttachment(res.execattachment) : [],
            };
            if (res.checkrecordid && res.checkcontent) {
              let content = res.checkcontent ? JSON.parse(res.checkcontent) : {};
              let dataSource = [];
              dataSource = content.schema
                .filter((item) => item.component != 'Divider')
                .map((item) => {
                  return {
                    ...item,
                    result: content.content[item.field]?.value,
                    description: content.content[item.field]?.description,
                    images: returnImages(content.content[item.field]?.images),
                  };
                });
              checkFormData.value = {
                ...res,
                content: content,
                dataSource: mergeSameValueRow(dataSource, 'parentGroupName'),
              };
              console.log('checkFormData', checkFormData.value);
            }
          });
        }
      });

      /**
       * 合并数组data中指定field的值相同的行时, 需要计算rowSpan来实现
       */
      const mergeSameValueRow = (data, field) => {
        let count = 0; //重复项的第一项
        let indexCount = 1; //下一项
        while (indexCount < data.length) {
          var item = data.slice(count, count + 1)[0]; //获取没有比较的第一个对象
          if (!item[`rowSpan`]) {
            item[`rowSpan`] = 1; //初始化为1
          }
          if (item[field] === data[indexCount][field]) {
            //第一个对象与后面的对象相比，有相同项就累加，并且后面相同项设置为0
            item[`rowSpan`]++;
            data[indexCount][`rowSpan`] = 0;
          } else {
            count = indexCount;
          }
          indexCount++;
        }
        return data;
      };

      function onOkButtonClick() {
        emit('success');
        closeModal();
      }

      /**
       * 下载附件
       */
      function downloadFile(item) {
        downloadByUrl({ url: item.url, fileName: item.name });
      }

      /**
       * 返回JSON格式的附件信息数组
       */
      function returnAttachment(attachment) {
        return JSON.parse(attachment).map((item) => {
          let url = uploadUrl + getFileApi + item.id;
          let title = item.name + '.' + item.type;
          return {
            ...item,
            title,
            url,
          };
        });
      }

      /**
       * 返回JSON格式的图片信息数组
       */
      function returnImages(images) {
        return images.map((item) => {
          let url = uploadUrl + getFileApi + item.id;
          let title = item.name + '.' + item.type;
          return {
            ...item,
            title,
            url,
          };
        });
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      return {
        moment,
        downloadFile,
        qcUnifyProps,
        getImageFileUrlPrefix,
        taskExecuteInfo,
        register,
        registerViewCheckFormModal,
        closeModal,
        displayModuleTitle,
        onOkButtonClick,
        checkFormData,
        registerCheckFormTable,
      };
    },
  });
</script>
<style scoped>
  .flex-row {
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
  }
  .Alist {
    flex: 1;
    margin-left: 10px;
    padding: 0 10px;
    border-left: 1px solid rgb(247, 247, 247);
  }
  .checkFormItem {
    font-size: 14px;
    margin: 5px;
  }
  .ant-image {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
  .flex-row {
    display: flex;
    align-items: center;
    flex-direction: row;
  }
  .fileIconList {
    margin: 8px;
    font-size: 25px;
    color: #5ca6ff;
  }
</style>
